Skip to main content

Dockerizing a Java

Now there are two ways this can be done,

1) Copy only the Jar file​

this is the more Viable solution as it also keeps less files in the image

FROM openjdk:20-jdk

EXPOSE 8080

ARG JAR\_FILE=target/\*.jar

COPY ${JAR\_FILE} app.jar

ENTRYPOINT \["java", "-jar", "/app.jar"\]

Here's the walk through

  1. Set the base image to openJDK

  2. expose port 8080

  3. Create a variable called JAR_FILE,

  4. copy JAR_FILE from the root and rename it to app.jar, IE the command looks like so: COPY target/*.jar app.jar

  5. Run app.jar once the Image is run

Here's what the folders look like (simplified)

|-src

|-target

|--build.jar

|-pom.xml

|-dockerfile

2) Copy Entire project​

Here's what that'll look like for a spring boot app

FROM openjdk:20-jdk

EXPOSE 8080

COPY . /app

WORKDIR /app

RUN MVN INSTALL

RUN MVN BUILD

ENTRYPOINT \["MVN", "springboot:run"\]

Basically we:

  1. Set base image to openJDK

  2. expose 8080

  3. copy everything to /app

  4. set our work DIR to /app

  5. run maven install

  6. run maven build

  7. and set our entry point to mvn springboot:run

Finally we can build and run it like so

docker build -t imagename . 

docker run imagename